#!/usr/bin/env python3
"""
Simple example workflow for ComfyUI-HunyuanWorld
This demonstrates how to use the nodes programmatically.
"""

import torch
from PIL import Image
import numpy as np

def create_sample_image():
    """Create a sample image for testing"""
    # Create a simple gradient image
    width, height = 512, 512
    image = np.zeros((height, width, 3), dtype=np.uint8)
    
    # Create a gradient
    for y in range(height):
        for x in range(width):
            image[y, x] = [
                int(255 * x / width),      # Red gradient
                int(255 * y / height),     # Green gradient
                128                        # Blue constant
            ]
    
    return Image.fromarray(image)

def example_simplified_workflow():
    """Example using the simplified wrapper"""
    print("🎯 Example: Simplified Wrapper Workflow")
    
    try:
        # Import the nodes (this would normally be done by ComfyUI)
        import sys
        import os
        sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        
        from __init__ import HunyuanWorldSimplifiedWrapper
        
        # Create sample input
        sample_image = create_sample_image()
        
        # Convert PIL image to ComfyUI tensor format
        image_np = np.array(sample_image).astype(np.float32) / 255.0
        image_tensor = torch.from_numpy(image_np).unsqueeze(0)  # Add batch dimension
        
        # Create the node
        wrapper = HunyuanWorldSimplifiedWrapper()
        
        # Generate 3D
        result_info, preview = wrapper.simple_generate(
            image=image_tensor,
            model_variant="mini",
            resolution=1024,
            enable_texture=True,
            filename_prefix="example_simple"
        )
        
        print(f"✅ Result: {result_info}")
        print(f"📸 Preview shape: {preview.shape}")
        
    except Exception as e:
        print(f"❌ Error in simplified workflow: {e}")

def example_real_pipeline_workflow():
    """Example using the real Hunyuan3D pipeline"""
    print("\n🔥 Example: Real Pipeline Workflow")
    
    try:
        import sys
        import os
        sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        
        from __init__ import HunyuanWorldModelLoader, HunyuanWorldImageTo3D
        
        # Create sample input
        sample_image = create_sample_image()
        image_np = np.array(sample_image).astype(np.float32) / 255.0
        image_tensor = torch.from_numpy(image_np).unsqueeze(0)
        
        # Load model
        loader = HunyuanWorldModelLoader()
        try:
            pipeline = loader.load_model(
                model_name="tencent/Hunyuan3D-2mini",
                precision="fp16",
                enable_texture=True,
                low_vram_mode=True
            )[0]  # Get the pipeline from tuple
            
            # Generate 3D
            generator = HunyuanWorldImageTo3D()
            mesh_path, info, preview = generator.generate_3d(
                pipeline=pipeline,
                image=image_tensor,
                apply_texture=True,
                save_mesh=True,
                filename_prefix="example_real",
                seed=42
            )
            
            print(f"✅ Mesh saved to: {mesh_path}")
            print(f"📋 Info: {info}")
            print(f"📸 Preview shape: {preview.shape}")
            
        except RuntimeError as e:
            if "Hunyuan3D libraries not available" in str(e):
                print("⚠️  Hunyuan3D libraries not installed. This is expected in test environment.")
                print("   Install with: pip install -r requirements.txt")
            else:
                raise e
        
    except Exception as e:
        print(f"❌ Error in real pipeline workflow: {e}")

def example_hybrid_workflow():
    """Example using the hybrid approach"""
    print("\n🔀 Example: Hybrid Workflow")
    
    try:
        import sys
        import os
        sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        
        from __init__ import HunyuanWorldHybridNode
        
        # Create sample input
        sample_image = create_sample_image()
        image_np = np.array(sample_image).astype(np.float32) / 255.0
        image_tensor = torch.from_numpy(image_np).unsqueeze(0)
        
        # Create hybrid node
        hybrid = HunyuanWorldHybridNode()
        
        # Try direct pipeline mode
        mesh_path, preview, method_info = hybrid.hybrid_generate(
            mode="direct_pipeline",
            image=image_tensor,
            model_name="tencent/Hunyuan3D-2mini",
            use_texture=True,
            filename_prefix="example_hybrid"
        )
        
        print(f"✅ Method: {method_info}")
        print(f"📁 Mesh path: {mesh_path}")
        print(f"📸 Preview shape: {preview.shape}")
        
    except Exception as e:
        print(f"❌ Error in hybrid workflow: {e}")

def main():
    """Run all examples"""
    print("🌍 ComfyUI-HunyuanWorld Example Workflows")
    print("=" * 50)
    
    # Run examples
    example_simplified_workflow()
    example_real_pipeline_workflow()
    example_hybrid_workflow()
    
    print("\n🎉 Examples completed!")
    print("\n💡 Tips:")
    print("- Install full dependencies for real functionality")
    print("- Check README.md for complete usage instructions")
    print("- See example_workflows.json for ComfyUI workflow examples")

if __name__ == "__main__":
    main()
